using System.Web.UI.WebControls;
using System.Web;
using System.Web.UI;
using System.IO;

namespace Enterprise.Adapters
{
    /// <summary>
    /// This is to cope with postbacks and the URL rewriter - without it the urls revert to 
    /// their original form on postback and this can cause viewstate errors
    /// </summary>
    public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            base.Render(new RewriteFormHtmlTextWriter(writer));
        }
    }

    public class RewriteFormHtmlTextWriter : HtmlTextWriter
    {
        public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
            : base(writer)
        {
            InnerWriter = writer.InnerWriter;
        }
        public RewriteFormHtmlTextWriter(TextWriter writer)
            : base(writer)
        {
            InnerWriter = writer;
        }

        public override void WriteAttribute(string name, string value, bool fEncode)
        {
          
            if (name == "action")
            {
                HttpContext Context = HttpContext.Current;

                if (Context.Items["ActionAlreadyWritten"] == null)
                {

                    // Use of the original url
                    value = Context.Request.RawUrl;
                    Context.Session["OriginalURL"] = value;

                    // Indicate that we//ve already rewritten the <form>//s action attribute to prevent
                    // us from rewriting a sub-control under the <form> control
                    Context.Items["ActionAlreadyWritten"] = true;
                }
            }

            base.WriteAttribute(name, value, fEncode);
        }
    }
}